<template>
  <div class="comment-detail">
    <h2>课程评论管理</h2>
    <p>当前课程ID：{{ courseId }}</p>

    <!-- 新增一级评论 -->
    <el-form :inline="true" @submit.prevent>
      <el-form-item>
        <el-input v-model="newCommentContent" placeholder="请输入评论内容" style="width: 400px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAddComment" :loading="addLoading">发表评论</el-button>
      </el-form-item>
    </el-form>

    <!-- 主评论卡片列表 -->
    <div v-for="item in commentList" :key="item.id" class="main-comment-card">
      <div class="main-comment-header">
        <span class="main-comment-content">{{ item.content }}</span>
        <span class="main-comment-meta"> {{ item.author }} </span>
        <el-button size="small" @click="openReplyDialog(item)">回复</el-button>
        <el-button size="small" type="danger" @click="handleDelete(item)">删除</el-button>
        <el-button size="small" type="primary" @click="toggleExpand(item)">
          {{ item._expanded ? '收起回复' : '查看回复' }}
        </el-button>
      </div>
      <div v-if="item._expanded && item.children && item.children.length" class="sub-comment-list">
        <el-card v-for="sub in item.children" :key="sub.id" class="sub-comment-card">
          <div class="sub-comment-content">{{ sub.content }}</div>
          <div class="sub-comment-meta"> {{ sub.author }} </div>
          <div class="sub-comment-actions">
            <el-button size="small" type="danger" @click="handleDelete(sub)">删除</el-button>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 回复弹窗 -->
    <el-dialog v-model="replyDialogVisible" title="回复评论" width="400px">
      <el-input v-model="replyContent" type="textarea" :rows="3" placeholder="请输入回复内容" />
      <template #footer>
        <el-button @click="replyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleReply" :loading="replyLoading">回复</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getReplyListService, addReplyService, deleteReplyService } from '@/apis/reply'
import { useRoute } from 'vue-router'

const route = useRoute()
const courseId = route.params.courseId
const commentList = ref([])
const loading = ref(false)
const newCommentContent = ref('')
const addLoading = ref(false)
const replyDialogVisible = ref(false)
const replyContent = ref('')
const replyLoading = ref(false)
let replyParent = null // 当前回复的父评论
let replyRoot = null // 一级评论对象（用于二级回复）

// 获取评论树
const getCommentList = async () => {
  loading.value = true
  try {
    const res = await getReplyListService({ courseId, pageNum: 1, pageSize: 20 })
    if (res.code === 1000) {
      // 增加 _expanded 字段用于展开/收起
      commentList.value = (res.data || []).map(item => ({ ...item, _expanded: false }))
    }
  } finally {
    loading.value = false
  }
}

// 新增一级评论
const handleAddComment = async () => {
  if (!newCommentContent.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  addLoading.value = true
  try {
    // postUserId 需后端鉴权或前端传递，这里用1做演示
    const res = await addReplyService({
      content: newCommentContent.value,
      courseId,
      postUserId: 1
    })
    if (res.code === 1000) {
      ElMessage.success('评论成功')
      newCommentContent.value = ''
      getCommentList()
    }
  } finally {
    addLoading.value = false
  }
}

// 展开/收起二级评论
const toggleExpand = (item) => {
  item._expanded = !item._expanded
}

// 打开回复弹窗
const openReplyDialog = (row, root = null) => {
  replyDialogVisible.value = true
  replyContent.value = ''
  replyParent = row
  replyRoot = root
}

// 回复评论（支持二级）
const handleReply = async () => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }
  replyLoading.value = true
  try {
    // postUserId/replyUserId 需后端鉴权或前端传递，这里用1做演示
    const res = await addReplyService({
      content: replyContent.value,
      courseId,
      postUserId: 1,
      parentId: replyParent.id,
      replyUserId: replyParent.postUserId
    })
    if (res.code === 1000) {
      ElMessage.success('回复成功')
      replyDialogVisible.value = false
      getCommentList()
    }
  } finally {
    replyLoading.value = false
  }
}

// 删除评论
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该评论及其所有子评论吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await deleteReplyService(row.id)
    if (res.code === 1000) {
      ElMessage.success('删除成功')
      getCommentList()
    }
  })
}

onMounted(() => {
  getCommentList()
})
</script>

<style scoped>
.comment-detail {
  padding: 20px;
}
.main-comment-card {
  background: #fff;
  border: 1px solid #e6e6e6;
  border-radius: 6px;
  margin-bottom: 18px;
  box-shadow: 0 2px 8px #f0f1f2;
  padding: 16px;
}
.main-comment-header {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}
.main-comment-content {
  font-weight: bold;
  font-size: 16px;
  margin-right: 16px;
}
.main-comment-meta {
  color: #888;
  font-size: 13px;
  margin-right: 16px;
}
.sub-comment-list {
  margin-top: 12px;
  margin-left: 32px;
}
.sub-comment-card {
  margin-bottom: 10px;
  background: #f8faff;
}
.sub-comment-content {
  font-size: 15px;
  margin-bottom: 4px;
}
.sub-comment-meta {
  color: #888;
  font-size: 12px;
}
.sub-comment-actions {
  margin-top: 4px;
}
</style> 